/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-01-28 22:37:58
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-03-12 20:33:09
 * @FilePath: \utils_react_manager\app\src\views\Word\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Button, Select, Form, Input, Table, Space, Pagination, Popover, Tag, Progress } from 'antd';
import dayjs from 'dayjs';
import type { ColumnsType } from 'antd/es/table';
import CusModal from '@/components/CusModal';
import WordComp from './components/WordComp';
import WordState from '@/store/Word';
import { SOURCE_OPTIONS, SOURCE_KEYS, getProperty } from './contants';
import { IPageParams } from './interface';

import './index.less';

const Word:React.FC = () => {
  console.log();
  
  // 弹框
  const [isWordModalOpen, setIsWordModalOpen] = useState(false);
  // 更新单词项
  const [currentItem, setCurrentItem] = useState<any>({});
  // 分页配置
  const [pageConfig, setPageConfig] = useState<IPageParams>({
      pageNo: 1,
      pageSize: 10,
      loading: false
    });

  // 获取仓库数据
  const { wordList, count } = useSelector((state: RootState) => ({
    ...state.word
  }));

  // 修改仓库数据
  const dispatch = useDispatch();

  // 获取单词列表dispatch
  const getWordList = useCallback(
    (values: IPageParams) => {
      dispatch(
        (dis: Function) => WordState?.mutations?.getWordList(dis, values)
      );
    },
    []
  );

  // 新增单词 显示弹框
  const handleAddWord = useCallback(
    () => {
      setIsWordModalOpen(true);
    },
    [isWordModalOpen]
  );

  // 取消弹框
  const handleCancel = useCallback(
    () => {
      setIsWordModalOpen(false);
      setCurrentItem({});
    },
    [isWordModalOpen, currentItem]
  );

  // 取消单词
  const handleCancelModal = useCallback(
    (value: boolean) => {
      setIsWordModalOpen(value);
      setCurrentItem({});
      getWordList({
        pageNo: pageConfig.pageNo,
        pageSize: pageConfig.pageSize
      });
    },
    [isWordModalOpen, currentItem, getWordList, pageConfig]
  );

  // 搜索
  const handleFinish = useCallback(
    (values: IWordListPayload) => {
      getWordList({
        ...values,
        pageNo: pageConfig.pageNo,
        pageSize: pageConfig.pageSize
      });
    },
    [getWordList, pageConfig]
  );

  // 分页器
  const handleTableChange = useCallback(
    (pageNo: number, pageSize: number) => {
      setPageConfig({
        ...pageConfig,
        pageNo: pageNo,
        pageSize: pageSize
      });
      getWordList({ pageNo, pageSize });
    },
    [pageConfig, getWordList]
  );

  // 更新单词
  const handleUpdateWord = useCallback(
    (values: IWordListItem) => {
      setCurrentItem({
        ...values
      });
      setIsWordModalOpen(true);
    },
    [currentItem, isWordModalOpen]
  );

  // 弹框标题
  const modalTip = useMemo(
    () => {
      const key = Object.keys(currentItem);
      return key.length ? '更新单词' : '新增单词';
    },
    [currentItem]
  );

  // 表格
  const columns: ColumnsType<IWordListItem> = useMemo(
    () => {
      return [
        {
          title: '序号',
          dataIndex: 'id',
          key: 'id',
          align: 'center'
        },
        {
          title: '英文',
          dataIndex: 'name',
          key: 'name',
          align: 'center'
        },
        {
          title: '音标',
          dataIndex: 'voice',
          key: 'voice',
          align: 'center'
        },
        {
          title: '描述',
          dataIndex: 'explain',
          key: 'explain',
          align: 'center',
          render: record => {

            return (
              <Popover content={record}>
                <div className='overflow-text'>{ record }</div>
              </Popover>
            );
          }
        },
        {
          title: '来源',
          dataIndex: 'source',
          key: 'source',
          align: 'center',
          render: record => {
            const color = record === 'basis' ? 'blue' : record === 'core' ? 'green' : 'red';
            return (
              <Tag color={color} key={record}>
                {getProperty(SOURCE_KEYS, record)}
              </Tag>
            );
          }
        },
        {
          title: '熟悉程度',
          dataIndex: 'count',
          key: 'count',
          align: 'center',
          render: record => {
            const percent = record * 10;
            return (
              <Progress width={50} type="circle" percent={percent} />
            );
          }
        },
        {
          title: '更新日期',
          dataIndex: 'updateTime',
          key: 'updateTime',
          align: 'center',
          render: record => {
            const timme = dayjs(record).format('YYYY-MM-DD HH:mm:ss');
            return timme;
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          render: record => {
            return (
              <Space size="middle">
                <Button onClick={() => handleUpdateWord(record)}>更新</Button>
                <Button>删除</Button>
              </Space>
            );
          },
        },
      ];
    },
    []
  );

  useEffect(
    () => {
      getWordList({
        pageNo: pageConfig.pageNo,
        pageSize: pageConfig.pageSize
      });
    },
    []
  );
  return (
    <div className="word-page-container">
      {/* 头部 */}
      <div className="word-header-container">
        {/* 筛选 */}
        <div className="word-filter-option">
          <Form
            onFinish={handleFinish}
            autoComplete="off"
          >
            <Form.Item
              label="数据来源"
              name="source"
            >
              <Select allowClear placeholder="请选择数据来源" options={SOURCE_OPTIONS} />
            </Form.Item>

            <Form.Item
              label="关键词"
              name="name"
            >
              <Input placeholder="请输入关键词" />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit">
                搜索
              </Button>
            </Form.Item>
          </Form>
        </div>
        {/* 功能 */}
        <div className="word-opear-option">
          <Button type="primary" onClick={handleAddWord}>新增</Button>
          <CusModal
            destroyOnClose
            className="word-cus-model"
            title={modalTip}
            open={isWordModalOpen}
            onCancel={handleCancel}
            cancelText="取消"
            okText="确定"
            footer={null}
          >
            <WordComp item={currentItem} onCancel={handleCancelModal} />
          </CusModal>
        </div>
      </div>
      {/* 表格 */}
      <div className="word-list-container">
        <Table
          bordered
          rowKey="id"
          columns={columns}
          dataSource={wordList}
          pagination={false}
          loading={pageConfig.loading}
        />
        <Pagination
          hideOnSinglePage
          current={pageConfig?.pageNo}
          pageSize={pageConfig?.pageSize}
          pageSizeOptions={[10, 20, 50, 100]}
          total={count}
          onChange={handleTableChange}
        />
      </div>
    </div>
  );
};

export default Word;